<?php
class ProductController extends ImpSoft_Controller_Action {

	public function init() {
		
		parent::init();
		$this->ctgyTbl = new Category;
		$this->prodTbl = new Product;
		$this->cartTbl = new Cart;
	
	}
	/**
	 * Product category page
	 */
	public function categoryAction() {
	
		$slug = $this->getRequest()->getParam('slug');
		$page = $this->getRequest()->getParam('page');
		if ($category = $this->ctgyTbl->fetchBySlug($slug)) {
			$this->view->category = $category->toArray();
			$select = $this->ctgyTbl->fetchProductsByCategorySlug($slug);
			$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
			// @todo Eventually this should come from db settings
			$paginator->setItemCountPerPage(25);
			$paginator->setCurrentPageNumber($page);
			$this->view->products = $paginator;
		} else {
			$this->flash('The category you requested doesn\'t exist', 'error');
			$this->goToRoute('home');
		}
	
	}

	/**
	 * Product detail page
	 */
	public function detailAction() {
	
		$addtocart = array();
		$errors = array();
		$slug = $this->getRequest()->getParam('slug');
		if ($product = $this->prodTbl->fetchBySlug($slug)) {
			$this->view->product = $product->toArray();
		} else {
			$this->flash('The product you requested doesn\'t exist', 'error');
			$this->goToRoute('home');
		}
		if ($this->isPost()) {
			$post = $this->getPost();
			$rules = with(new Q_Rule_Set())
				->add(new Q_Rule_Digits(), 'quantity', 'Please enter how many you would like.');
			if ($rules->validate($post)) {
				//$this->getCart()->addProduct($post['product_id']);
				pre($this->getCart());
			} else {
				$errors = $rules->getErrors();
			}
			$addtocart = $post;
		}
		$this->view->addtocart = $addtocart;
		$this->view->errors = $errors;
	
	}

}